package com.wangyadong.hobby.concurrent;

import com.wangyadong.hobby.thread.ReentrantLock;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.stream.IntStream;

import static com.wangyadong.hobby.concurrent.CountDownLatchDemo.PRINT_CONSUMER;

public class ReentrantLockDemo2 {
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition EMPTY_CONDITION = lock.newCondition();
    private static final Condition FULL_CONDITION = lock.newCondition();
    private static final LinkedList<Integer> list = new LinkedList<>();

    public static void main(String[] args) {

        IntStream.range(0, 20).forEach(i -> {
            new Thread(() -> {
                change(i);
            }).start();
        });
        IntStream.range(0, 20).forEach(i -> {
            new Thread(() -> {
                use();
            }).start();
        });

    }


    public static void change(int i) {
        try {
            lock.lock();
            while (list.size() >= 10) {
                FULL_CONDITION.await();
            }
            list.add(i);
            PRINT_CONSUMER.accept("------------shareData----------------" + i);
            EMPTY_CONDITION.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void use() {
        try {
            lock.lock();
            while (list.isEmpty()) {
                EMPTY_CONDITION.await();
            }
            PRINT_CONSUMER.accept("------------CONSUMER----------------" + list.removeFirst());
            FULL_CONDITION.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
